#!/bin/bash

show_usage()
{
    echo "
    ./build.sh <target>
    target:
        isa:        build rv32ui isa test cases
        simple-asm: build simple-asm test case
        simple-c:   build simple-c test case
    "
    exit
}

do_post_make()
{
    riscv32-unknown-elf-objdump -d ${elf_name} > ./${dump_name}
    riscv32-unknown-elf-objcopy -O binary -R .note -R .comment -S ${elf_name} ${bin_name}
    riscv32-unknown-elf-readelf -a ${elf_name} > ./${elf_info_name}
}


elf_name="${1}.elf"
elf_info_name="${1}.elf.info"
dump_name="${1}.dump"
bin_name="${1}.bin"

tools_root=${EASY_RISCV_SW_ROOT}
if [ ! -d "$tools_root" ]; then
    echo "$tools_root do not exist, please check env variable: EASY_RISCV_SW_ROOT"
    exit
fi

convert=$tools_root/scripts/convert-sim.py

isa_make_dir=$tools_root/riscv-tests
isa_bin_dir=$isa_make_dir/isa/
simple_asm_make_dir=$tools_root/simple-asm
simple_asm_bin_dir=$simple_asm_make_dir/build/
simple_c_make_dir=$tools_root/simple-c
simple_c_bin_dir=$simple_c_make_dir/build/

if [ $# -eq 1 ]; then
    if [[ "$1" == "isa" ]]; then
        pushd $isa_make_dir
        ./configure --with-xlen=32
        make clean
        make
        pushd
        python3 $convert -d $isa_bin_dir

    elif [[ "$1" == "simple-asm" ]]; then
        pushd $simple_asm_make_dir
        rm -rf build
        mkdir -p build
        pushd build
        riscv32-unknown-elf-as  ../src/$1.S -o ${elf_name}
        do_post_make
        pushd +2  #return where we call build.sh
        python3 $convert -d $simple_asm_bin_dir

    elif [[ "$1" == "simple-c" ]]; then
        pushd $simple_c_make_dir
        rm -rf build
        mkdir -p build
        pushd build
        cmake -D BIN_NAME=$1 ../src
        make
        do_post_make
        pushd +2  #return where we call build.sh
        python3 $convert -d $simple_c_bin_dir
    else
        show_usage
    fi

else
    show_usage
fi
